package com.zhkj.txg.module.member.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.zhkj.lib.base.BalanceChangeEvent
import com.zhkj.lib.base.MemberStatusChangeEvent
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.member.vm.MemberCardViewModel
import com.zhkj.txg.module.order.entity.OrderAddressEntity
import com.zhkj.txg.module.order.entity.OrderPayEntity
import com.zhkj.txg.module.order.ui.AddressManagerActivity
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.PayUtils
import com.zhkj.txg.utils.WXPayEntity
import kotlinx.android.synthetic.main.fragment_member_pay.*
import kotlinx.android.synthetic.main.item_order_address.*
import kotlinx.android.synthetic.main.item_order_goods.*

class MemberPayFragment : ViewModelFragment<MemberCardViewModel>() {
    override fun setViewModel(): MemberCardViewModel = createViewModel(true)

    override val layoutResId: Int = R.layout.fragment_member_pay

    private val requestCodeAddress = 1010

    override fun initUI() {
        // 选择地址按钮
        viewAddress.setOnClickListener {
            AddressManagerActivity.selectAddress(this, requestCodeAddress)
        }
        btnBalancePay.setOnClickListener {
            btnBalancePay.isSelected = true
            btnAliPay.isSelected = false
            btnWxPay.isSelected = false
        }
        btnAliPay.setOnClickListener {
            btnBalancePay.isSelected = false
            btnAliPay.isSelected = true
            btnWxPay.isSelected = false
        }
        btnWxPay.setOnClickListener {
            btnBalancePay.isSelected = false
            btnAliPay.isSelected = false
            btnWxPay.isSelected = true
        }
        // 支付按钮
        tvMemberPay.setOnClickListener {
            if (viewModel.defaultAddressLiveData.value?.response?.data == null) {
                toast(getString(R.string.select_address))
                return@setOnClickListener
            }
            viewModel.memberOrderPay(
                when {
                    btnWxPay.isSelected -> OrderPayEntity.TYPE_WECHAT
                    btnAliPay.isSelected -> OrderPayEntity.TYPE_ALIPAY
                    else -> OrderPayEntity.TYPE_BALANCE
                }
            )
        }
    }

    override fun initData() {
        viewModel.defaultAddress()
        // 显示商品金额
        tvMemberPay.text = getString(R.string.member_pay_hint, viewModel.productUIEntity?.productTotalAmount)
        // 默认选中余额支付
        btnBalancePay.isSelected = true
        ImageUtils.loadRoundCornerImage(this, ivOrderGoods, viewModel.productUIEntity?.productImg ?: "")
        tvOrderGoodsName.text = viewModel.productUIEntity?.productName
        tvOrderGoodsPrice.text = SpanUtil.setMoneySymbol(viewModel.productUIEntity?.productPrice ?: "0.0")
        tvOrderGoodsNumber.text = "x${viewModel.productUIEntity?.productNumber ?: 0}"
        tvTotalAmount.text = getString(R.string.total_count, viewModel.productUIEntity?.productNumber ?: 0)
        tvShopTotalFreight.text = SpanUtil.setMoneySymbol(viewModel.productUIEntity?.productTotalAmount ?: "0.0")
    }

    override fun initViewModel() {
        viewModel.defaultAddressLiveData.observe(this, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                fillAddress(it.response?.data)
            }
        })
        // 微信支付结果观察者
        viewModel.payResult().observe(this, Observer {
            if (it.paySuccess) {
                // 支付成功，跳转支付成功页面
                paySuccess()
            } else toast(it.payDesc)
        })
        viewModel.orderPayLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let { order ->
                if (!order.isNeedPay) {
                    // 余额刷新
                    RxBus.post(BalanceChangeEvent())
                    // 支付成功，跳转支付成功页面
                    paySuccess()
                } else when (order.payType) {
                    // 微信支付
                    OrderPayEntity.TYPE_WECHAT -> {
                        order.payInfo.let {
                            PayUtils.wxPay(requireContext(), Gson().fromJson(it, WXPayEntity::class.java))
                        }
                    }
                    // 支付宝支付
                    OrderPayEntity.TYPE_ALIPAY -> PayUtils.aliPay(requireActivity(), order.payInfo, {
                        // 支付成功，跳转支付成功页面
                        paySuccess()
                    }, { toast(it) })
                    else -> Unit
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == requestCodeAddress) {
            val address = data?.getSerializableExtra("data") as OrderAddressEntity
            viewModel.defaultAddressLiveData.value?.response?.data = address
            fillAddress(address)
        }
    }

    private fun paySuccess() {
        // 会员状态刷新
        RxBus.post(MemberStatusChangeEvent())
        AccountManager.saveMemberStatus(true)
        // 跳转支付成功页面
        viewModel.fragmentChangeLiveData.value = true
    }

    private fun fillAddress(address: OrderAddressEntity?) {
        if (address != null) {
            tvOrderAddressName.visibility = View.VISIBLE
            tvOrderAddressName.text = address.consignee
            tvOrderAddressMobile.visibility = View.VISIBLE
            tvOrderAddressMobile.text = address.mobile
            tvOrderAddress.text = address.address
        } else {
            tvOrderAddressName.visibility = View.GONE
            tvOrderAddressMobile.visibility = View.GONE
            tvOrderAddress.text = getString(R.string.select_address)
        }
    }
}